﻿@using Components.TestServer.Services
@attribute [StreamRendering]
<p>Streaming component with persistent state</p>

<p>This component demonstrates state persistence alongside streaming rendering. When the component first renders, it'll emit a message "streaming" and yield until its notified via a call to <code>/persistent-state/end-streaming</code>. When the component renders it will try to restore the state and if present display that it succeded in doing so and the restored value. If the state is not present, it will indicate it didn't find it and display a "fresh" value.</p>

<p id="interactive">Interactive: @(RendererInfo.IsInteractive)</p>
@if (_streaming)
{
    <p id="streaming">Streaming: @_streaming</p>
}
else
{
    <p id="interactive-runtime">Interactive runtime: @_interactiveRuntime</p>
    <p id="state-value">State value:@EnhancedNavState</p>
}

<a id="enhanced-nav-update" href="@Navigation.GetUriWithQueryParameter("server-state", "updated")">With updated server state</a>
<br />


@code {

    private bool _streaming;
    private string _interactiveRuntime;

    [Inject] public AsyncOperationService StreamingManager { get; set; }

    [Inject] public NavigationManager Navigation { get; set; }

    [Parameter] public string StreamingId { get; set; }

    [Parameter] public string ServerState { get; set; }

    [PersistentState(AllowUpdates = true)]
    public string EnhancedNavState { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (string.IsNullOrEmpty(StreamingId))
        {
            throw new InvalidOperationException("StreamingId is required.");
        }

        if (!RendererInfo.IsInteractive)
        {
            _interactiveRuntime = "none";
            _streaming = true;
            await StreamingManager.Start(StreamingId);
            _streaming = false;
            EnhancedNavState = ServerState;
        }
        else
        {
            EnhancedNavState ??= "not found";
            _interactiveRuntime = OperatingSystem.IsBrowser() ? "wasm" : "server";
        }
    }
}
